﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETDBModel;
using System.Text;
using System.Web.UI.HtmlControls;


public partial class _Default : System.Web.UI.Page
{
    BL bl = new BL();
    DAL dl = new DAL();
    int summOfTest;

    protected void Page_Init(object sender, EventArgs e)
    {
 
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {
            
            plhAllContent.Visible = true;

            if (!IsPostBack)
            {
                plhChosenTest.Visible = false;
                Dictionary<aspnet_TestCategory, List<aspnet_Tests>> dictCatAndTests = bl.CreateDictAllCatAndTests();
                if (Session["AllTestId"] == null)
                {
                    Session.Add("AllTestId", dl.SelectAllTestId());
                }
                if (Session["allCatAndTests"] == null)
                {
                    Session.Add("allCatAndTests", dictCatAndTests);
                }
                rptrLeftMenu.DataSource = dictCatAndTests;
                rptrLeftMenu.DataBind();

                if (!string.IsNullOrEmpty(Request.QueryString["test"]) && (Session["AllTestId"] as List<string>).Contains(Request.QueryString["test"]))
                {
                    lblVisitors.Visible = false;
                    plhChosenTest.Visible = true;
                    string testId = Request.QueryString["test"];
                    CreateSession(bl.CreateDictAllAnswAndQuest(User.Identity.Name, testId));
                    GetQuestion();
                    GetAnswer();
                    lblPaging.Text = Session["page"].ToString() + "/" + Session["CountOfPage"].ToString();
                    lblTestName.Text = dl.SelectTestNameByID(testId);
                }
                else
                {
                    lblVisitors.Visible = true;
                }
            }

        }
        else
        {
            plhAllContent.Visible = false;
        }


    }
    protected void upStars_Load(object sender, EventArgs e)
    {
        if (lblPrevRate.Text == "Рейтинг всего теста:")
        {
            hidChnRate.Value = "1";
            rptrLeftMenu.DataSource = (Session["allCatAndTests"] as Dictionary<aspnet_TestCategory, List<aspnet_Tests>>);
            rptrLeftMenu.DataBind();
            dl.SetTestVote(Request.QueryString["test"], Convert.ToInt32(hidInpRating.Value));
        }
    }


    /// <summary>
    /// Bind Left Menu items
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rptrLeftMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblCat") as Label;
        if (l != null)
        {
            KeyValuePair<aspnet_TestCategory, List<aspnet_Tests>> kvp = (KeyValuePair<aspnet_TestCategory, List<aspnet_Tests>>)e.Item.DataItem;
            l.Text = kvp.Key.CategoryName;

            for (int i = 0; i < kvp.Value.Count; i++)
            {
                Literal litbr = new Literal();
                litbr.Text = "<br/>";
                HyperLink hl = new HyperLink();
                hl.NavigateUrl = "Default.aspx?test=" + kvp.Value[i].TestId;
                hl.Text = kvp.Value[i].Name;
                rptrLeftMenu.Controls.Add(litbr);
                rptrLeftMenu.Controls.Add(hl);

            }

        }
    }


    /// <summary>
    /// Create all Session
    /// </summary>
    /// <param name="dictAnswerAndQuest">dictionary of all answer and question</param>
    private void CreateSession(Dictionary<aspnet_TestQuestions, List<aspnet_Answers>> dictAnswerAndQuest)
    {
        Session.Add("page", 1);
        Session.Add("CountOfPage", dictAnswerAndQuest.Count);
        Session.Add("allAnswAndQuest", dictAnswerAndQuest);
        Session.Add("RatingQuest", 0);
        Session.Add("SumOfTest", 0);
    }

    /// <summary>
    /// Get Quesstion
    /// </summary>
    public void GetQuestion()
    {
        aspnet_TestQuestions quest = bl.GetCurrentQuestionFromSession(Session["allAnswAndQuest"], Session["page"]);
        lblQuestRes.Text = dl.SelectValueVotesByQuestID(quest.QuestionId.ToString());
        lblQuest.Text = quest.Question;
    }

    /// <summary>
    /// Get Answer
    /// </summary>
    public void GetAnswer()
    {
        RadioButtonList1.DataSource = bl.GetCurrentAnswersFromSession(Session["allAnswAndQuest"], Session["page"]);
        RadioButtonList1.DataTextField = "Answer";
        RadioButtonList1.DataValueField = "AnswerId";
        RadioButtonList1.DataBind();
    }


    protected void btnCompleteTest_Click(object sender, EventArgs e)
    {
        int page = Convert.ToInt32(Session["page"]);
  
        if (hidChnRate.Value == "1" && !string.IsNullOrEmpty(hidInpRating.Value))
        {
            aspnet_TestQuestions quest = bl.GetCurrentQuestionFromSession(Session["allAnswAndQuest"], Session["page"]);
            dl.InsertVoteQuestion(quest.TestId, quest.QuestionId, Convert.ToInt32(hidInpRating.Value));
        }

        if (page < Convert.ToInt32(Session["CountOfPage"]))
        {
            if (RadioButtonList1.SelectedIndex != -1)
            {

                List<aspnet_Answers> tempListAnsw = bl.GetCurrentAnswersFromSession(Session["allAnswAndQuest"], Session["page"]);
                summOfTest = Convert.ToInt32(Session["SumOfTest"]);
                summOfTest += dl.SelectPointsByAnswerID(RadioButtonList1.SelectedValue);
                page++;
                Session["page"] = page;
                Session["SumOfTest"] = summOfTest;
                GetAnswer();
                GetQuestion();
                lblPaging.Text = Session["page"].ToString() + "/" + Session["CountOfPage"].ToString();
            }
        }
        else
        {
            RadioButtonList1.Visible = false;
            btnCompleteTest.Visible = false;
            lblQuest.Visible = false;
            lblPaging.Text = "";

            lblQuestRes.Text = dl.SelectTestVote(Request.QueryString["test"]);
            lblPrevRate.Text = "Рейтинг всего теста:";
            btnCompleteTest.Text = "Завершить тест";
            lblResult.Text = "<h2>Результаты теста:</h2>" + dl.SelectResultByTest(Request.QueryString["test"], Convert.ToInt32(Session["SumOfTest"]));
            dl.InsertUserTestResult(Request.QueryString["test"], dl.SelectUserIdByName(User.Identity.Name), Convert.ToInt32(Session["SumOfTest"]));
        }



        hidInpRating.Value = null;

    }


}
